package com.example.gate.controller;

import com.example.game.LoginRequest;
import com.example.game.LoginResponse;
import com.example.game.UserInfo;
import com.example.game.proto.internal.SrvResp;
import com.example.gate.grpc.SeverGrpcClient;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 游戏API控制器
 * 提供HTTP接口，内部通过gRPC调用lobby服务
 */
@Slf4j
@RestController
@RequestMapping("/api/game")
@RequiredArgsConstructor
public class GameController {

    @Autowired
    private final SeverGrpcClient gameGrpcClient;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> request) {
        String userId = request.get("userId");
        String token = request.get("token");

        log.info("收到登录请求: userId={}", userId);
        LoginRequest login = LoginRequest.newBuilder().setUserId(userId).setToken(token).build();
        SrvResp srvResp = gameGrpcClient.sendMessageToLobby(2001, Integer.parseInt(userId), login.toByteArray());

        Map<String, Object> result = new HashMap<>();
        result.put("ret", srvResp.getRet());
        if (srvResp.getRet() != 0) return result;

        try {
            LoginResponse response = LoginResponse.parseFrom(srvResp.getBody());
            if (response.getSuccess() && response.hasUserInfo()) {
                UserInfo userInfo = response.getUserInfo();
                Map<String, Object> userData = new HashMap<>();
                userData.put("userId", userInfo.getUserId());
                userData.put("username", userInfo.getUsername());
                userData.put("level", userInfo.getLevel());
                userData.put("coins", userInfo.getCoins());
                result.put("userInfo", userData);
            }
        } catch (InvalidProtocolBufferException e) {
            log.error(e.getMessage());
        }

        return result;
    }

    @PostMapping("/loginTset")
    public Map<String, Object> login1(@RequestBody Map<String, String> request) {
        String userId = request.get("userId");
        String token = request.get("token");

        log.info("收到登录请求: userId={}", userId);
        LoginRequest login = LoginRequest.newBuilder().setUserId(userId).setToken(token).build();
        gameGrpcClient.sendMessageToLobbyAsync(2002, Integer.parseInt(userId), login.toByteArray());


        Map<String, Object> result = new HashMap<>();
        result.put("ret", 1);
        return result;
    }


    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "gate-service");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    /**
     * 健康检查
     */
    @GetMapping("/test")
    public Map<String, Object> test() {
        Map<String, Object> result = new HashMap<>();

        try {
            String path = "/api/game/health";
            Map<RequestMappingInfo, HandlerMethod> handlerMethods =
                    requestMappingHandlerMapping.getHandlerMethods();


            Optional<HandlerMethod> matched = handlerMethods.entrySet().stream()
                    .filter(entry -> entry.getKey().getPathPatternsCondition() != null)
                    .filter(entry -> entry.getKey().getPathPatternsCondition().getFirstPattern().getPatternString().equals(path))
                    .map(Map.Entry::getValue)
                    .findFirst();
            if (matched.isEmpty()) return result;
            HandlerMethod handlerMethod =  matched.get().createWithResolvedBean();
            Method method = handlerMethod.getMethod();
            Object bean = handlerMethod.getBean();

            Object invoke = method.invoke(bean);
            System.out.println();


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

} 